#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <dirent.h>
#include <signal.h>

int main(int argc, char *argv[]) {
    DIR *dir;
    struct dirent *entry;
    char path[1024];

    dir = opendir("/proc");
    if (!dir) {
        perror("opendir");
        return 1;
    }

    if (argc == 2) {
        // If a PID is provided as a command-line argument, kill that process
        int pid_to_kill = atoi(argv[1]);
        if (pid_to_kill > 0) {
            if (kill(pid_to_kill, SIGTERM) == 0) {
                printf("Process with PID %d killed successfully.\n", pid_to_kill);
            } else {
                perror("kill");
                printf("Failed to kill process with PID %d.\n", pid_to_kill);
            }
            closedir(dir);
            return 0;
        } else {
            printf("Invalid PID provided.\n");
            closedir(dir);
            return 1;
        }
    }

    printf("PID\tName\n");
    while ((entry = readdir(dir)) != NULL) {
        if (entry->d_type == DT_DIR) {
            int pid = atoi(entry->d_name);
            if (pid != 0) {
                snprintf(path, sizeof(path), "/proc/%s/cmdline", entry->d_name);
                FILE *file = fopen(path, "r");
                if (file) {
                    char cmdline[1024];
                    if (fgets(cmdline, sizeof(cmdline), file)) {
                        printf("%d\t%s\n", pid, cmdline);
                    }
                    fclose(file);
                }
            }
        }
    }
    closedir(dir);
    return 0;
}
